package com.example.netty.io.core

import io.netty.channel.Channel
import java.io.Closeable
import java.io.IOException
import java.util.concurrent.atomic.AtomicBoolean

/**
 * File Name :NioSocketTask
 * Author : qihualu
 * Date : 2024/4/15
 * Desc :
 **/

abstract class NioSocketTask : Closeable, Runnable {

    protected var channel: Channel? = null
    protected val isClose = AtomicBoolean(false)
    protected val isRelease = AtomicBoolean(false)
    protected var retryTimes = 0
    fun canRetry(): Boolean {
        return !isRelease.get() && retryTimes < NettyConfigure.maxRetryCount
    }

    override fun close() {
        NettyLog.d("NioSocketTask", "stop: ")
        if (isClose.compareAndSet(false, true)) {
            try {
                channel?.close()
                channel = null
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }

    fun onSuccess(channel: Channel) {
        this.retryTimes = 0
        this.channel = channel
    }

    abstract fun release()
}